#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class YunnanCgqrmzf03B8Policy(BaseTaxPolicySpider):
    name = "yunnan_cgqrmzf_03b8_policy"

    province: str = "云南省"  # 取表格
    city: str = "昆明市"  # 取表格
    county: str = "呈贡区"  # 取表格
    park: str = "None"  # 取表格
    source: str = "呈贡区人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.kmcg.gov.cn/zfxxgk/zcwj/qzfwj/"  # 注明入口网址，以便后续排错

    def start_requests(self):
        url = self.url + 'index.shtml'
        yield scrapy.Request(url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div//a[(contains(@href, 'htm') or @title) and not(contains(./text(), '部门解读'))]/ancestor::div[string-length(string(.))>=10]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            print(item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下一页' in response.text:
                total_page = response.xpath(""".""").re_first(r"""\s*/\s*(\d+)页""")
                for page_num in range(1, int(int(total_page) / 1 + 2)):
                    yield response.follow(re.sub(r"index\.", r"index_{}.".format(page_num), response.url),
                                          callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl yunnan_cgqrmzf_03b8_policy".split())
